import db from './db.js';

let currentTab = 'recent';

document.addEventListener('DOMContentLoaded', async () => {
  const openNewTabCheckbox = document.getElementById('openNewTab');
  const closeTabsAfterSaveCheckbox =
    document.getElementById('closeTabsAfterSave');
  const recentTabButton = document.getElementById('recentTab');
  const favoriteTabButton = document.getElementById('favoriteTab');
  const openPageTypeRadios = document.getElementsByName('openPageType');

  // 加载保存的设置
  const tabGroups = await db.getAllTabGroups();
  const settings = await db.getSettings();
  openNewTabCheckbox.checked = settings?.openNewTab ?? true;
  closeTabsAfterSaveCheckbox.checked = settings?.closeTabsAfterSave ?? true;
  openPageTypeRadios.forEach((radio) => {
    radio.checked = radio.value === (settings?.openPageType || 'blank');
  });

  // 保存设置
  openNewTabCheckbox.addEventListener('change', async () => {
    await db.updateSettings({
      openNewTab: openNewTabCheckbox.checked
    });
  });

  closeTabsAfterSaveCheckbox.addEventListener('change', async () => {
    await db.updateSettings({
      closeTabsAfterSave: closeTabsAfterSaveCheckbox.checked
    });
  });

  // 保存页面类型设置
  openPageTypeRadios.forEach((radio) => {
    radio.addEventListener('change', async () => {
      await db.updateSettings({
        openPageType: radio.value
      });
    });
  });

  // 标签页切换事件
  recentTabButton.addEventListener('click', () => {
    currentTab = 'recent';
    recentTabButton.classList.add('active');
    favoriteTabButton.classList.remove('active');
    showTabGroups();
  });

  favoriteTabButton.addEventListener('click', () => {
    currentTab = 'favorite';
    favoriteTabButton.classList.add('active');
    recentTabButton.classList.remove('active');
    showTabGroups();
  });

  // 添加事件委托处理标签组和标签页的按钮点击
  document.getElementById('tabGroups').addEventListener('click', async (e) => {
    const target = e.target;
    const button = target.closest('button');
    if (!button) return;

    if (button.matches('.restore-group-btn')) {
      const groupId = Number(button.dataset.groupId);
      await restoreTabGroup(groupId);
    } else if (button.matches('.delete-group-btn')) {
      const groupId = Number(button.dataset.groupId);
      await deleteTabGroup(groupId);
    } else if (button.matches('.open-tab-btn')) {
      const groupId = Number(button.closest('.tab-group').dataset.groupId);
      const tabIndex = parseInt(button.dataset.tabIndex);
      await openSingleTab(groupId, tabIndex);
    } else if (button.matches('.delete-tab-btn')) {
      const groupId = Number(button.closest('.tab-group').dataset.groupId);
      const tabIndex = parseInt(button.dataset.tabIndex);
      await deleteTabFromGroup(groupId, tabIndex);
    } else if (button.matches('.favorite-btn')) {
      const groupId = Number(button.closest('.tab-group').dataset.groupId);
      await toggleFavorite(groupId);
    }
  });

  // 切换收藏状态
  async function toggleFavorite(groupId) {
    try {
      const tabGroups = await db.getAllTabGroups();
      const group = tabGroups.find((g) => g.id === groupId);

      if (!group) return;

      group.favorite = !group.favorite;
      await db.updateTabGroup(group);
      showTabGroups();
    } catch (error) {
      console.error('切换收藏状态时出错：', error);
    }
  }

  const closeAndSaveButton = document.getElementById('closeAndSave');

  // 关闭并保存标签页
  closeAndSaveButton.addEventListener('click', async () => {
    try {
      // 获取当前窗口除新标签页外的所有标签页
      const tabs = await chrome.tabs.query({ currentWindow: true });

      // 保存标签组信息
      const tabGroup = {
        id: Date.now(),
        name: new Date().toLocaleString(),
        tabs: tabs.map((tab) => ({
          url: tab.url,
          title: tab.title,
          favIconUrl: tab.favIconUrl || '',
        })),
        favorite: false,
      };

      // 添加新的标签组
      await db.addTabGroup(tabGroup);

      // 如果需要关闭标签页
      if (closeTabsAfterSaveCheckbox.checked) {
        await Promise.all(
          tabs.map((tab) => {
            chrome.tabs.remove(tab.id);
          }),
        );
      }

      // 如果需要打开新标签页
      if (openNewTabCheckbox.checked) {
        const openPageType =
          Array.from(openPageTypeRadios).find((radio) => radio.checked)
            ?.value || 'blank';
        if (openPageType === 'manager') {
          await chrome.tabs.create({ url: 'manager.html' });
        } else {
          await chrome.windows.create({ focused: true });
        }
      }

      // 等待窗口创建完成
      await new Promise((resolve) => setTimeout(resolve, 500));

      // 刷新标签组列表
      showTabGroups();
    } catch (error) {
      console.error('关闭并保存标签页时出错：', error);
    }
  });

  // 初始化时显示标签组列表
  showTabGroups();
});

// 显示保存的标签组
async function showTabGroups() {
  try {
    const tabGroups = await db.getAllTabGroups();
    const tabGroupsContainer = document.getElementById('tabGroups');
    const filteredGroups =
      currentTab === 'favorite'
        ? tabGroups.filter((group) => group.favorite)
        : tabGroups;

    // 按时间戳（id）降序排序
    filteredGroups.sort((a, b) => b.id - a.id);

    tabGroupsContainer.innerHTML = filteredGroups
      .map(
        (group) => `
      <div class="tab-group" data-group-id="${group.id}">
        <div class="tab-group-header">
          <div>
            <h4 class="tab-group-title">${group.name}</h4>
            <span class="tab-count">${group.tabs.length} 个标签页</span>
          </div>
          <div class="tab-group-actions">
            <button class="favorite-btn icon-btn ${
              group.favorite ? 'active' : ''
            }" data-group-id="${group.id}">
              <img src="images/icons/star.svg" alt="收藏" class="icon">
            </button>
            <button class="restore-group-btn small" data-group-id="${
              group.id
            }">恢复</button>
            <button class="delete-group-btn small danger" data-group-id="${
              group.id
            }">删除</button>
          </div>
        </div>
        <div class="tab-list">
          ${group.tabs
            .map(
              (tab, index) => `
            <div class="tab-item">
              <img src="${
                tab.favIconUrl || 'images/icon16.png'
              }" alt="" style="width: 16px; height: 16px;">
              <span class="tab-title">${tab.title}</span>
              <div class="tab-actions">
                <button class="open-tab-btn icon-btn" data-group-id="${
                  group.id
                }" data-tab-index="${index}">
                  <img src="images/icons/visit.svg" alt="打开" class="icon">
                </button>
                <button class="delete-tab-btn icon-btn danger" data-group-id="${
                  group.id
                }" data-tab-index="${index}">
                  <img src="images/icons/trash.svg" alt="删除" class="icon">
                </button>
              </div>
            </div>
          `,
            )
            .join('')}
        </div>
      </div>
    `,
      )
      .join('');
  } catch (error) {
    console.error('显示标签组时出错：', error);
  }
}

// 恢复标签组
async function restoreTabGroup(groupId) {
  try {
    const tabGroups = await db.getAllTabGroups();
    const group = tabGroups.find((g) => g.id === groupId);
    if (!group) return;

    // 创建新窗口并打开所有标签页
    const window = await chrome.windows.create();
    await Promise.all(
      group.tabs.map((tab) =>
        chrome.tabs.create({
          windowId: window.id,
          url: tab.url,
        }),
      ),
    );

    // 关闭新窗口创建时的空白标签页
    const tabs = await chrome.tabs.query({ windowId: window.id });
    if (tabs.length > 0) {
      await chrome.tabs.remove(tabs[0].id);
    }
  } catch (error) {
    console.error('恢复标签组时出错：', error);
  }
}

// 打开单个标签页
async function openSingleTab(groupId, tabIndex) {
  try {
    const tabGroups = await db.getAllTabGroups();
    const group = tabGroups.find((g) => g.id === groupId);
    if (!group || !group.tabs[tabIndex]) return;

    // 检查是否已存在相同URL的标签页
    const existingTabs = await chrome.tabs.query({});
    const existingTab = existingTabs.find(
      (tab) => tab.url === group.tabs[tabIndex].url,
    );

    if (existingTab) {
      // 如果存在相同URL的标签页，则激活该标签页
      await chrome.tabs.update(existingTab.id, { active: true });
      await chrome.windows.update(existingTab.windowId, { focused: true });
    } else {
      // 如果不存在，则创建新标签页
      await chrome.tabs.create({
        url: group.tabs[tabIndex].url,
      });
    }
  } catch (error) {
    console.error('打开标签页时出错：', error);
    alert('打开标签页失败：' + error.message);
  }
}

// 删除标签组
async function deleteTabGroup(groupId) {
  try {
    if (!confirm('确定要删除这个标签组吗？')) return;
    await db.deleteTabGroup(groupId);
    await showTabGroups();
  } catch (error) {
    console.error('删除标签组时出错：', error);
    alert('删除标签组失败：' + error.message);
  }
}

// 从标签组中删除标签页
async function deleteTabFromGroup(groupId, tabIndex) {
  try {
    const tabGroups = await db.getAllTabGroups();
    const group = tabGroups.find((g) => g.id === groupId);
    if (!group) return;

    group.tabs.splice(tabIndex, 1);
    if (group.tabs.length === 0) {
      await db.deleteTabGroup(groupId);
    } else {
      await db.updateTabGroup(group);
    }
    showTabGroups();
  } catch (error) {
    console.error('删除标签页时出错：', error);
  }
}
